<template>
  <div style="background-color: #F3F5F7;">
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <div style="padding: 0 12px 50px;">
        <Head />
        <Swipe />
        <Grid />
        <van-list

        v-model="loading" :finished="finished" offset=20 finished-text="没有更多了" @load="onLoad">
          <Content
          @addnum="insert_cart"
          @tiaz="tiaz"
          :cates="cates"/>
        </van-list>
      </div>
    </van-pull-refresh>
    <tabbar />
  </div>
</template>

<script>
import { fetchCates } from '@api'
import Tabbar from '@components/Tabbar.vue'
import Head from './components/head.vue'
import Swipe from './components/Swipe.vue'
import Grid from './components/grid.vue'
import Content from './components/content.vue'
import { Toast } from 'vant'
import { mapActions } from 'vuex'
export default {
  data () {
    return {
      cates: [],
      isLoading: false,
      page: 1,
      size: 4,
      loading: false,
      finished: false,
      list: []
    }
  },
  created () {

  },
  methods: {
    ...mapActions([
      'insert_cart'
    ]),
    tiaz (id) {
      this.$router.push({
        path: '/details',
        query: {
          id: id
        }
      })
    },
    fetchCates () {
      fetchCates({ page: this.page, size: this.size }).then(res => {
        this.isLoading = false // 请求时，isloading 为true，请求完成以后将isloading设置为false
        this.loading = false
        if (res.data.code === 200) {
          this.cates = [...this.cates, ...res.data.data]
        }
        if (res.data.data.length < 1) { // 当请求每一页的数据，如果返回的数组为空，那么就完成了所有的请求数据，将finished 设置为true，不能继续进行向下滚动
          this.finished = true
          console.log('到底了')
        }
      })
    },
    onRefresh () {
      this.cates = [] // 下拉刷新的时候 将数据清空 重新请求数据，请求成功以后将isloading 设置为false 以便下次重新请求
      this.page = 1 // 下拉刷新只用请求第一次的数据
      this.finished = false
      this.fetchCates() // 请求成功以后，弹出刷新提示框
      Toast('刷新成功')
      this.page++ // 将请求数据加一 ，方便滚动时请求数据
    },
    onLoad () {
    // 当进入页面时，会先请求一次数据
      this.fetchCates() // 向下滚动时 请求数据，
      this.page++ // 请求成功以后将请求数据加1，方便向下滚动时 继续请求下一页数
    }
  },

  components: {
    Tabbar,
    Head,
    Swipe,
    Grid,
    Content
  }
}
</script>

<style lang="scss" scoped>
</style>
